package com.ws.ssmzongjie3.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.ssmzongjie3.bean.*;
import com.ws.ssmzongjie3.service.Acl_RoleService;
import com.ws.ssmzongjie3.service.Acl_UserService;
import com.ws.ssmzongjie3.service.BusinessService;
import com.ws.ssmzongjie3.util.Res;
import com.ws.ssmzongjie3.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/houuser")
public class Acl_UserController {
    @Autowired
    private Acl_UserService houUserService;
    @Autowired
    private Acl_RoleService acl_RoleService;
    @Autowired
    private BusinessService businessService;
    @RequestMapping("/houlogin")
    public String houlogin(Acl_User houUser, HttpSession session) {
        System.out.println(houUser+"======================");
        Acl_User userByName = houUserService.getUserByName(houUser);
        System.out.println(userByName+"==============");
        boolean verify = false;
        if (userByName != null){

             verify = SecurityUtils.verify(houUser.getPassword(), userByName.getPassword());
        }
        System.out.println(verify);
        if (verify){
            List<Acl_Permission> permissions = houUserService.listPermissionsByUserId(userByName);
            ArrayList<String> strings = new ArrayList<>();
            for (Acl_Permission permission : permissions) {
                strings.add(permission.getPath());
            }


            session.setAttribute("permissions",strings);
            session.setAttribute("houuser",userByName);
//            permissions
            return "redirect:/houtai/houshouye";
        }

        return "houlogin";
    }
    @RequestMapping("/add")
    public String add(Model model) {
        List<Business> businesses = businessService.listBusiness(new Business());
        model.addAttribute("businesses",businesses);
        return "WEB-INF/admin/acl_user/add";
    }

    @RequestMapping("/insert")
    public String zhuce(Acl_User houUser, MultipartFile image) throws IOException {
        String encrypt = SecurityUtils.encrypt(houUser.getPassword());
        houUser.setPassword(encrypt);
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());

            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            houUser.setAcl_user_avatar(fileName);
        }
        houUserService.insertUser(houUser);
        return "redirect:/houuser/list";
    }

    @RequestMapping("/huixian")
    public String huixian(Acl_User houUser, Model model) {
        Acl_User userById = houUserService.getUserById(houUser);
        List<Business> businesses = businessService.listBusiness(new Business());
        model.addAttribute("user",userById);
        model.addAttribute("businesses",businesses);
        return "/WEB-INF/admin/acl_user/update";
    }
    @RequestMapping("/update")
    public String update(Acl_User houUser, MultipartFile image) throws IOException {
        System.out.println(image);
        System.out.println(houUser);
        if (houUser.getPassword()!=null){
            String encrypt = SecurityUtils.encrypt(houUser.getPassword());
            houUser.setPassword(encrypt);
        }
    
        // 获取旧用户信息
        Acl_User oldUser = houUserService.getUserById(houUser);
        // 如果上传了新图片
        if ((image.getSize() != 0)||!(image.getOriginalFilename().equals(""))){
            // 删除旧图片
            if (oldUser != null && oldUser.getAcl_user_avatar() != null && !oldUser.getAcl_user_avatar().isEmpty()) {
                File oldAvatarFile = new File(Res.fileDir + oldUser.getAcl_user_avatar());
                if (oldAvatarFile.exists()) {
                    oldAvatarFile.delete();
                }
            }
    
            // 保存新图片
            System.out.println("文本框名字"+image.getName());
            System.out.println("文件名字"+image.getOriginalFilename());
            System.out.println("文件大小"+image.getSize());
            System.out.println("文件格式"+image.getContentType());
    
            String uuid = UUID.randomUUID().toString().replace("-", "");
            System.out.println(uuid);
            String fileName = uuid+"."+image.getOriginalFilename().split("\\.")[1];
            System.out.println(fileName);
            image.transferTo(new File(Res.fileDir+fileName));
            houUser.setAcl_user_avatar(fileName);
        }
    
        houUserService.updateUser(houUser);
        return "redirect:/houuser/list";
    }
    @RequestMapping("/delete")
    public String delete(Acl_User houUser) {
        // 获取用户信息
        Acl_User user = houUserService.getUserById(houUser);
        // 删除用户
        houUserService.deleteById(houUser);
        // 如果用户有头像，删除对应的图片文件
        if (user != null && user.getAcl_user_avatar() != null && !user.getAcl_user_avatar().isEmpty()) {
            File avatarFile = new File(Res.fileDir + user.getAcl_user_avatar());
            if (avatarFile.exists()) {
                avatarFile.delete();
            }
        }
        return "redirect:/houuser/list";
    }
    @RequestMapping("/list")
    public String select(Model model, ProVo proVo, Acl_User user){
        System.out.println("links:"+user);
        PageHelper pageHelper = new PageHelper();//分页帮助类
        pageHelper.startPage(proVo.getCurrentPage(),proVo.getPageSize());//分页   每页条数
        List<Acl_User> aclUsers = houUserService.listUserWithMerchant(user);
        PageInfo pageInfo = new PageInfo(aclUsers);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("user",user);

        return "WEB-INF/admin/acl_user/list";
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public Map<String, Boolean> checkUsername(@RequestParam String username,@RequestParam Integer userId) {
        Map<String, Boolean> response = new HashMap<>();
        Acl_User aclUser = new Acl_User();
        aclUser.setUsername(username);
        if (userId != null && userId != 0){
            aclUser.setAcl_user_id(userId);
        }
        Acl_User userById = houUserService.getUserById(aclUser);
        Acl_User userByName = houUserService.getUserByName(aclUser);
        boolean exists = userByName != null;
        if (userById != null){
            if (userById.getUsername().equals(username)){
                exists = false;
            }
        }

        response.put("exists", exists);
        return response;
    }


    @RequestMapping("/tuichu")
    public String tuichu(HttpSession session){
        session.removeAttribute("houuser");
        return "redirect:/houuser/houlogin";
    }

}
